import React, { useEffect, useState, useCallback } from 'react'
import { useSelector } from 'react-redux'
import {
  Layout,
  Menu,
  Button,
  Message,
  Input,
  Tooltip,
  Tag,
  Empty,
  Divider,
  Typography,
  Collapse,
  Alert,
  Trigger,
  List,
} from '@arco-design/web-react'
import { IconHome, IconCalendar, IconPlus, IconCheck } from '@arco-design/web-react/icon'
// import Scroller from '@components/Scroller'
import '@arco-design/web-react/dist/css/arco.css'
import './index.css'
import Avatar from '@arco-design/web-react/es/Avatar/avatar'
import UserCard from './UserCard'
import {
  getFriendAndGroupListApi,
  getRequestFriendListApi,
  receiveFriendRequestApi,
  rejectFriendRequestApi,
} from '@@/src/api/chat'
import Search from './Search'
import Scroller from './Scroller'
const CollapseItem = Collapse.Item

const InputSearch = Input.Search

const MenuItem = Menu.Item

const Sider = Layout.Sider
const Header = Layout.Header
const Footer = Layout.Footer
const Content = Layout.Content

// 组件定义
function Messenger(props) {
  const [id, setId] = React.useState(0)
  const [type, setType] = React.useState('0')
  const [name, setName] = React.useState('')
  const [avatar, setAvatar] = React.useState('未知')
  // const [tag, setTag] = React.useState()
  const [reqList, setReqList] = React.useState([])
  const [loading, setLoading] = React.useState(false)

  useEffect(() => {
    const { id, type, name, tag, avatar } = props.history.location.state || { id: '-1', type: '0', name: '' }
    setId(id)
    setType(type)
    setName(name)
    setAvatar(avatar)
  }, [props.history.location.state])

  const customStyle = {
    border: 'none',
  }

  const numberStyle = {
    fontSize: 12,
    color: '#999999',
    border: 'none',
  }

  const userStore = useSelector((state) => state.user)
  const { id: currentUser } = userStore.info
  const [friendList, setFriendList] = useState([])
  const [onlineNum, setOnlineNum] = useState(0)
  const [groupList, setGroupList] = useState([])

  const renderUserActions = (id, status) => {
    const handleReject = (id) => {
      rejectFriendRequestApi({ userId: id, friendId: currentUser })
        .then((res) => {
          if (res.data) {
            Message.success('已拒绝好友申请')
            fetchData()
          }
        })
        .catch((err) => Message.error('拒绝异常'))
    }
    const handleReceive = (id) => {
      receiveFriendRequestApi({ userId: id, friendId: currentUser })
        .then((res) => {
          if (res.data) {
            Message.success('已同意好友申请')
            fetchData()
          }
        })
        .catch((err) => Message.error('同意异常'))
    }
    return (
      <div>
        <Button size='mini' type='primary' status='danger' onClick={() => handleReject(id)}>
          拒绝
        </Button>
        <Divider type='vertical' />
        <Button size='mini' type='primary' onClick={() => handleReceive(id)}>
          同意
        </Button>
      </div>
    )
  }

  const fetchData = useCallback(() => {
    if (currentUser === -1) {
      return
    }
    // 请求接口
    const getFriendAndGroupList = async () => {
      let result = await getFriendAndGroupListApi({ userId: currentUser })
      return result?.data || []
    }

    const getRequestFriendList = async () => {
      let result = await getRequestFriendListApi({ userId: currentUser })
      return result?.data || []
    }

    const fetchList = async () => {
      // 获取好友分组列表
      const result = await getFriendAndGroupList()
      console.log(getFriendAndGroupList, result)
      setFriendList(result.friendList)
      setOnlineNum(result.onlineNum)
      setGroupList(result.groupList)
      // 获取好友申请列表
      const reqListResult = await getRequestFriendList()
      setReqList(reqListResult)
    }
    fetchList()
  }, [currentUser])

  useEffect(() => {
    fetchData()
  }, [fetchData])

  const ReqList = () => {
    return (
      <div className='demo-trigger-popup' style={{ width: 350 }}>
        <List
          bordered={false}
          split={false}
          loading={loading}
          size={'small'}
          scrollLoading={true}
          pagination={reqList.length <= 5 ? false : { pageSize: 5, total: reqList.length }}
          dataSource={reqList}
          render={(item, index) => (
            <List.Item key={index} actions={[renderUserActions(item.id, item.status)]}>
              <List.Item.Meta
                avatar={
                  <Avatar shape='square'>
                    {item.avatar ? <img alt='avatar' src={item.avatar} /> : item.name.slice(0, 1)}
                  </Avatar>
                }
                title={item.name}
                description={item.description}
              />
            </List.Item>
          )}
          noDataElement={<div>没有找到哦~</div>}
        />
      </div>
    )
  }

  // 停止滚动时显示滚动条的功能
  const [scrollTop, setScrollTop] = React.useState(0)
  const [scrollEnd, setScrollEnd] = React.useState(true)
  const scrollRef = React.useRef()
  let timeout = null
  const onScrollHandle = () => {
    if (scrollEnd !== false) {
      setScrollEnd(false)
    }
    if (timeout) {
      clearTimeout(timeout)
    }
    timeout = setTimeout(() => {
      if (scrollEnd !== true) {
        setScrollEnd(true)
        setScrollTop(scrollRef.current?.scrollTop || 0)
      }
    }, 200)
  }

  return (
    <Layout className='chat-main'>
      {/* 左边 */}
      <Sider className='chat-left' resizeDirections={['right']} style={{ minWidth: 290, maxWidth: 490 }}>
        <div className='chat-contacts'>
          {/* 搜索区域 */}
          <div className='contacts-search'>
            {/* 搜索区左边 搜索框*/}
            <div className='contacts-search-container'>
              <InputSearch allowClear placeholder='搜索' style={{ width: 220 }}></InputSearch>
            </div>
            {/* 搜索区右边 按钮*/}
            <div className='contacts-add'>
              <Button shape='circle' icon={<IconPlus />} />
            </div>
          </div>
          {/* 搜索区下方 */}
          <div className='chat-contacts-menu' style={{ height: '100%' }}>
            {reqList.length > 0 && (
              <Alert
                type='info'
                style={{ fontSize: 12 }}
                content={`您收到了${reqList.length}条好友申请`}
                action={
                  <Trigger
                    trigger='click'
                    popup={() => <ReqList />}
                    mouseEnterDelay={100}
                    mouseLeaveDelay={100}
                    position='right'
                    popupAlign={
                      reqList.length === 1
                        ? {
                            right: [18, 25],
                          }
                        : {
                            right: [18, 60],
                          }
                    }
                  >
                    <Button size='mini' type='outline'>
                      查看申请
                    </Button>
                  </Trigger>
                }
              />
            )}
            <div
              className={`contacts-list scroller ${scrollEnd ? '' : 'scrolling'}`}
              ref={scrollRef}
              onScrollCapture={() => onScrollHandle()}
            >
              {/* 左边好友列表 */}
              <Collapse
                className={'chat-contacts-collapse'}
                bordered={false}
                defaultActiveKey={['friend', 'group']}
                style={{ maxWidth: 1180 }}
              >
                <CollapseItem
                  style={customStyle}
                  contentStyle={{ padding: 0 }}
                  header='我的好友'
                  name='friend'
                  extra={
                    <span className='cant-drag-and-select' style={numberStyle}>
                      {onlineNum}/{friendList.length}
                    </span>
                  }
                >
                  {friendList.map((item) => (
                    <UserCard key={item.id} feedItem={item} />
                  ))}
                </CollapseItem>
                <CollapseItem
                  style={customStyle}
                  contentStyle={{ padding: 0 }}
                  header='我的群组'
                  name='group'
                  extra={
                    <span className='cant-drag-and-select' style={numberStyle}>
                      {groupList.length}
                    </span>
                  }
                >
                  {groupList.map((item) => (
                    <UserCard key={item.id} feedItem={item} />
                  ))}
                </CollapseItem>
              </Collapse>
            </div>
          </div>
        </div>
      </Sider>
      {/* 右边 */}
      {id < 1 && (
        <Content>
          {/* <Empty
            imgSrc='https://sf3-cn.feishucdn.com/obj/goofy/ee/web-client/p/contents/contacts/static/img/no-oncall.ef4a63a1.png'
            description={<Button type='primary'>添加好友</Button>}
          /> */}
          <Search refreshList={fetchData} />
        </Content>
      )}
      {id >= 1 && (
        <Layout className='chat-right'>
          {/* 右侧内容 */}
          <Layout>
            <Header className='chat-window-header'>
              <div className='chat-window-haeder-main'>
                <div className='chat-window-haeder-left'>
                  <div className='chat-window-header-title cant-drag-and-select'>新的联系人</div>
                </div>
                <div className='chat-window-haeder-right'>
                  <div className='header-right-icon'>
                    <div className='button-hover-box'>
                      <Tooltip content='完成(Ctrl+D)' mini>
                        <IconCheck
                          fontSize={20}
                          onClick={() => {
                            Message.success('已完成')
                          }}
                          style={{ cursor: 'pointer' }}
                        />
                      </Tooltip>
                    </div>
                  </div>
                </div>
              </div>
            </Header>

            <Layout>
              <Content className='chatMessages'>1</Content>
              <Footer className='chatEditor'>2</Footer>
            </Layout>
          </Layout>
        </Layout>
      )}
    </Layout>
  )
}

export default Messenger
